/**
 * Sumpu Inc.
 * Copyright (c) 2011-2012 All Rights Reserved. 
 */
package cn.sumpu.app.guoguojie.biz.impl.top;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.TaobaokeReport;
import com.taobao.api.domain.TaobaokeReportMember;
import com.taobao.api.request.*;
import com.taobao.api.response.*;

import cn.sumpu.app.guoguojie.biz.*;
import cn.sumpu.app.guoguojie.constant.*;
import cn.sumpu.app.guoguojie.dao.*;
import cn.sumpu.app.guoguojie.domain.*;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.PageModel;
import cn.sumpu.app.guoguojie.util.ProductBs;

/**
 * @author nick
 * @version $Id: TopBizImpl.java, v 0.1 2012-8-13 上午11:40:20 nick Exp $
 */
public class TopBizImpl implements TopBiz {

    private final static Logger            logger    = LoggerFactory.getLogger(TopBizImpl.class);

    private static DecimalFormat           df        = new DecimalFormat("#.##");

    private String                         appkey    = null;
    private String                         appsecret = null;
    private String                         url       = null;
    private String                         pid       = null;

    private static BlockingQueue<Runnable> queue     = new ArrayBlockingQueue<Runnable>(100);
    private static ThreadPoolExecutor      exec      = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, queue);

    @Autowired
    private DoingBiz                       doingBiz;
    @Autowired
    private DoingDao                       doingDao;
    @Autowired
    private AccountBiz                     accountBiz;
    @Autowired
    private MessageBiz                     messageBiz;
    @Autowired
    private MemberBiz                      memberBiz;

    private TopDao                         topDao;

    private DataSourceTransactionManager   transactionManager;

    public void setTransactionManager(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public void setTopDao(TopDao topDao) {
        this.topDao = topDao;
    }

    public void setAppkey(String appkey) {
        this.appkey = appkey;
    }

    public void setAppsecret(String appsecret) {
        this.appsecret = appsecret;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    /**
     * @return
     * @see cn.sumpu.app.guoguojie.biz.TOPBiz#getAppkey()
     */
    @Override
    public String getAppkey() {
        return appkey;
    }

    /**
     * @return
     * @see cn.sumpu.app.guoguojie.biz.TOPBiz#getAppsecret()
     */
    @Override
    public String getAppsecret() {
        return appsecret;
    }

    /**
     * @return
     * @see cn.sumpu.app.guoguojie.biz.TOPBiz#getUrl()
     */
    @Override
    public String getUrl() {
        return url;
    }

    /**
     * @return
     * @see cn.sumpu.app.guoguojie.biz.TOPBiz#getPid()
     */
    @Override
    public String getPid() {
        return pid;
    }

    private boolean verifyGuoguojieCommissionRate(double guoguojieCommissionRate) {
        return !(0.01 < guoguojieCommissionRate && guoguojieCommissionRate < 1);
    }

    @Override
    public String genTaobaoLink(Member member, DoingProduct doingProduct, double guoguojieCommissionRate) throws AppBusinessException {
        if (null == member) {
            throw new AppBusinessException("Member is null,can't generate taobao link.");
        }
        if (null == doingProduct) {
            throw new AppBusinessException("Product is null,can't generate taobao link.");
        }
        if (!isTaobaoProduct(doingProduct)) {
            throw new AppBusinessException("Product is not taobao,can't generate taobao link.");
        }
        if (verifyGuoguojieCommissionRate(guoguojieCommissionRate)) {
            throw new AppBusinessException("Guoguojie commissionrate is incorrect [commissionrate=" + guoguojieCommissionRate + "]");
        }
        try {
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, appsecret);
            TaobaokeItemsConvertRequest req = new TaobaokeItemsConvertRequest();
            req.setFields("click_url");
            req.setNumIids(doingProduct.getOriginalId());
            req.setPid(Long.parseLong(pid));

            String rate = String.valueOf((int) Math.floor(guoguojieCommissionRate * 100));
            req.setOuterCode(member.getIdentifier() + rate);

            TaobaokeItemsConvertResponse res = client.execute(req);
            List<TaobaokeItem> ti = res.getTaobaokeItems();
            if (null != ti && ti.size() > 0) {
                TaobaokeItem t = ti.get(0);
                return t.getClickUrl();
            }
            return null;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("Can't generate taobao link.", e);
            }
            throw new AppBusinessException("Can't generate taobao link.");
        }
    }

    private boolean isTaobaoProduct(DoingProduct doingProduct) {
        return DoingProductFrom.TAOBAO.getValue().equals(doingProduct.getFrom());
    }

    @Override
    public String genTaobaoLink(String memberId, String originalId, double guoguojieCommissionRate) throws AppBusinessException {
        return genTaobaoLink(memberId, originalId, false, guoguojieCommissionRate);
    }

    @Override
    public String genTaobaoLink(String memberId, String originalId, Boolean isMobile, double guoguojieCommissionRate) throws AppBusinessException {
        if (null == memberId) {
            throw new AppBusinessException("Member id is null,can't generate taobao link.");
        }
        if (null == originalId) {
            throw new AppBusinessException("Product id is null,can't generate taobao link.");
        }
        if (verifyGuoguojieCommissionRate(guoguojieCommissionRate)) {
            throw new AppBusinessException("Guoguojie commissionrate is incorrect [commissionrate=" + guoguojieCommissionRate + "]");
        }
        try {
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, appsecret);
            TaobaokeItemsConvertRequest req = new TaobaokeItemsConvertRequest();
            req.setFields("click_url");
            req.setNumIids(originalId);
            req.setPid(Long.parseLong(pid));

            String rate = String.valueOf((int) Math.floor(guoguojieCommissionRate * 100));
            req.setOuterCode(memberId + rate);

            req.setIsMobile(isMobile);
            TaobaokeItemsConvertResponse res = client.execute(req);
            List<TaobaokeItem> ti = res.getTaobaokeItems();
            if (null != ti && ti.size() > 0) {
                TaobaokeItem t = ti.get(0);
                return t.getClickUrl();
            }
            return null;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("Can't generate taobao link.", e);
            }
            throw new AppBusinessException("Can't generate taobao link.");
        }
    }

    @Override
    public TaobaokeItem convertTaobaoke(String memberId, String originalId) throws AppBusinessException {
        if (null == memberId) {
            throw new AppBusinessException("Member id is null,can't convert taobaoke.");
        }
        if (null == originalId) {
            throw new AppBusinessException("Product id is null,can't convert taobaoke.");
        }
        try {
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, appsecret);
            TaobaokeItemsConvertRequest req = new TaobaokeItemsConvertRequest();
            req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
            req.setNumIids(originalId);
            req.setPid(Long.parseLong(pid));

            req.setOuterCode(memberId);

            TaobaokeItemsConvertResponse res = client.execute(req);
            List<TaobaokeItem> ti = res.getTaobaokeItems();
            if (null != ti && ti.size() > 0) {
                TaobaokeItem t = ti.get(0);
                return t;
            }
            return null;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("Can't convert taobaoke.", e);
            }
            throw new AppBusinessException("Can't convert taobaoke.");
        }
    }

    @Override
    public TaobaokeItem convertTaobaoke(Member member, DoingProduct doingProduct) throws AppBusinessException {
        if (null == member) {
            throw new AppBusinessException("Member is null,can't convert taobaoke.");
        }
        if (null == doingProduct) {
            throw new AppBusinessException("Product is null,can't convert taobaoke.");
        }
        if (!isTaobaoProduct(doingProduct)) {
            throw new AppBusinessException("Product is not taobao,can't convert taobaoke.");
        }
        try {
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, appsecret);
            TaobaokeItemsConvertRequest req = new TaobaokeItemsConvertRequest();
            req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
            req.setNumIids(doingProduct.getOriginalId());
            req.setPid(Long.parseLong(pid));

            req.setOuterCode(member.getIdentifier());

            TaobaokeItemsConvertResponse res = client.execute(req);
            List<TaobaokeItem> ti = res.getTaobaokeItems();
            if (null != ti && ti.size() > 0) {
                TaobaokeItem t = ti.get(0);
                return t;
            }
            return null;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("Can't convert taobaoke.", e);
            }
            throw new AppBusinessException("Can't convert taobaoke.");
        }
    }

    @Override
    public void refreshProduct(String message) {
        exec.submit(new RefreshTask(message));
    }

    private class RefreshTask implements Runnable {

        private String message;

        RefreshTask(String message) {
            this.message = message;
        }

        @Override
        public void run() {
            if (null == message) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Taobao message is null.");
                }
                return;
            }

            JSONObject jsonObj = (JSONObject) (JSONObject.fromObject(message));
            String notifyItem = jsonObj.getString("notify_item");
            JSONObject json = (JSONObject) (JSONObject.fromObject(notifyItem));
            String topic = json.getString("topic");
            String status = json.getString("status");
            String numIid = json.getString("num_iid");

            if (null == topic || null == status && null == numIid) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Topic || status || numIid is null,ignore taobao message(" + message + ")");
                }
                return;
            }

            if (!"item".equals(topic)) {// 只处理商品变更通知
                if (logger.isWarnEnabled()) {
                    logger.warn("Topic not's [item],ignore taobao message(" + message + ")");
                }
                return;
            }

            String changedFields = json.getString("changed_fields");

            if (null == changedFields || "".equals(changedFields)) {
                if (logger.isWarnEnabled()) {
                    logger.warn("ChangedFields is null,ignore taobao message(" + message + ")");
                }
                return;
            }

            String[] cArray = changedFields.split(",");

            if (null == cArray || cArray.length <= 0) {// 商品字段没有发生变化
                if (logger.isWarnEnabled()) {
                    logger.warn("ChangedFields not's correct value,ignore taobao message(" + message + ")");
                }
                return;
            }

            try {
                DoingProduct dp = doingBiz.getProductContain(DoingProductFrom.TAOBAO.getValue(), numIid);
                if (null == dp) {// 商品库没有对应的商品
                    if (logger.isWarnEnabled()) {
                        logger.warn("Guouojie's product is null,ignore taobao message(" + message + ")");
                    }
                    return;
                }

                if (isNoSale(status)) {
                    dp.setStatus(DoingProductStatus.NOSALE.getValue());
                    return;
                }

                for (String filed : cArray) {
                    if ("price".equals(filed)) {
                        String realPrice = json.getString(filed);
                        Double price = Double.valueOf(realPrice);
                        dp.setPrice(price);
                        Double maxPrice = dp.getMaxPrice();
                        if (price > maxPrice) {// 更新最大价格
                            dp.setMaxPrice(price);
                        }
                    } else if ("title".equals(filed)) {
                        dp.setName(filed);
                    }
                }

                doingDao.updateDoingProduct(dp);
            } catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error("Process taobao message(" + message + ") fail.", e);
                }
            }

        }

        private boolean isNoSale(String status) {
            return "ItemDownshelf".equals(status) || " ItemDelete".equals(status) || "ItemPunishDelete".equals(status) || "ItemPunishDownshelf".equals(status);
        }

    }

    @Override
    public void subscribe(DoingProduct doingProduct) {
        if (null == doingProduct) {
            if (logger.isWarnEnabled()) {
                logger.warn("Product is null,subscribe fail.");
                return;
            }
        }
        if (null == doingProduct.getOriginalId()) {
            if (logger.isWarnEnabled()) {
                logger.warn("Taobao product id is null,subscribe fail.");
                return;
            }
        }
        try {
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, appsecret);
            IncrementSubscriptionAddRequest req = new IncrementSubscriptionAddRequest();
            req.setTopic("item");
            req.setSubscribeKey("num_iid");
            req.setSubscribeValues(doingProduct.getOriginalId());
            IncrementSubscriptionAddResponse response = client.execute(req);
            Boolean flag = response.getIsSuccess();
            if (null != flag && flag) {
                doingProduct.setSubscribe("yes");
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("Subscribe taobao product fail.", e);
            }
        }
    }

    /**
     * @author BruceZhang
     * @param map   
     * @throws AppBusinessException
     */
    @Override
    public void obtainTaobaokeReport(String date, String sessionkey) throws Exception {
        long pageSize = 100;
        //取得昨天的日期
        //        String date = new SimpleDateFormat("yyyyMMdd").format(new Date().getTime() - (1000 * 60 * 60 * 24));
        TaobaokeReport r = getReport(date, pageSize, 1L, sessionkey);
        if (r == null || r.getTaobaokeReportMembers() == null) {
            return;
        }
        Long count = r.getTotalResults();
        long pages = (count + pageSize - 1) / pageSize;
        for (long j = 1; j <= pages; j++) {
            if (j > 1) {
                r = getReport(date, pageSize, j, sessionkey);
            }
            if (r != null && r.getTaobaokeReportMembers() != null) {
                List<TaobaokeReportMember> l = r.getTaobaokeReportMembers();
                //                Set<cn.sumpu.app.guoguojie.domain.TaobaokeReport> set = new HashSet<cn.sumpu.app.guoguojie.domain.TaobaokeReport>();
                for (int i = 0; i < l.size(); i++) {
                    TaobaokeReportMember trm = l.get(i);
                    cn.sumpu.app.guoguojie.domain.TaobaokeReport t = new cn.sumpu.app.guoguojie.domain.TaobaokeReport();
                    t.setTradeParentId(trm.getTradeParentId() == null ? "" : String.valueOf(trm.getTradeParentId()));
                    t.setTradeId(trm.getTradeId() == null ? "" : String.valueOf(trm.getTradeId()));
                    t.setRealPayFee(trm.getRealPayFee() == null ? 0.00 : Double.valueOf(trm.getRealPayFee()));
                    t.setCommissionRate(trm.getCommissionRate() == null ? "" : trm.getCommissionRate());
                    t.setCommission(trm.getCommission() == null ? 0.00 : Double.valueOf(trm.getCommission()));
                    t.setSubsidyRate(trm.getSubsidyRate() == null ? "" : trm.getSubsidyRate()); //
                    t.setSubsidy(trm.getSubsidy() == null ? 0.00 : Double.valueOf(trm.getSubsidy())); //
                    t.setAppKey(trm.getAppKey() == null ? "" : trm.getAppKey());
                    t.setOuterCode(trm.getOuterCode() == null ? "" : trm.getOuterCode());
                    t.setCreateTime(trm.getCreateTime());
                    t.setStatus(trm.getStatus() == null ? "" : trm.getStatus()); //
                    t.setConfirmTime(trm.getConfirmTime());
                    t.setPayTime(trm.getPayTime());
                    t.setPayPrice(trm.getPayPrice() == null ? 0.00 : Double.valueOf(trm.getPayPrice()));
                    t.setNumIid(trm.getNumIid() == null ? "" : String.valueOf(trm.getNumIid()));
                    t.setItemTitle(trm.getItemTitle() == null ? "" : trm.getItemTitle());
                    t.setItemNum(trm.getItemNum() == null ? 0 : trm.getItemNum());
                    t.setCategoryId(trm.getCategoryId() == null ? "" : String.valueOf(trm.getCategoryId()));
                    t.setCategoryName(trm.getCategoryName() == null ? "" : trm.getCategoryName());
                    t.setShopTitle(trm.getShopTitle() == null ? "" : trm.getShopTitle());
                    t.setSellerNick(trm.getSellerNick() == null ? "" : trm.getSellerNick());

                    DoingProduct dp = doingBiz.getProductContain(DoingProductFrom.TAOBAO.getValue(),
                        trm.getNumIid() == null ? "" : String.valueOf(trm.getNumIid()));
                    if (!Common.empty(dp) && !Common.emptyStr(dp.getIdentifier())) {
                        t.setGuoguojieProductId(dp.getIdentifier());
                    } else {
                        t.setGuoguojieProductId("");
                    }

                    String outerCode = trm.getOuterCode();
                    if (!Common.emptyStr(outerCode) && outerCode.length() >= 9) {
                        String memberId = outerCode.substring(0, 9);
                        if (!Common.emptyStr(memberId)) {
                            t.setMember(memberId);
                        } else {
                            t.setMember("");
                        }
                        String rate = outerCode.substring(9, outerCode.length());
                        if (!Common.emptyStr(rate)) {
                            Double rd = null;
                            if (rate.length() == 1) {
                                rd = Double.parseDouble("0.0" + rate);
                            } else {
                                rd = Double.parseDouble("0." + rate);
                            }
                            t.setGuoguojieCommissionRate(df.format(rd));
                        } else {
                            t.setGuoguojieCommissionRate("0.00");
                        }
                    } else {
                        t.setMember("");
                        t.setGuoguojieCommissionRate("0.00");
                    }
                    t.setGuoguojieRebate(false);
                    t.setGuoguojieCommission(0d);
                    try {
                        topDao.insertTaobaokeReport(t);//FIXME 以后再考虑批量插入
                    } catch (Exception e) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Insert taobaoke report fail," + t, e);
                        }
                    }

                    //                    set.add(t);
                }
                //                Map<String, Object> map = new HashMap<String, Object>();
                //                map.put("list", set);
                //                topDao.insertTaobaokeReports(map);
            }
        }
    }

    /**
     * @author BruceZhang
     * @param date          日期
     * @param pageSize      条数
     * @param pageNo        页数
     * @return  报表
     * @throws Exception
     */
    @Override
    public TaobaokeReport getReport(String date, Long pageSize, Long pageNo, String sessionkey) throws AppBusinessException {
        if (Common.emptyStr(sessionkey)) {
            throw new AppBusinessException("Taobao sessionkey is null");
        }
        try {
            TaobaoClient client = new DefaultTaobaoClient(getUrl(), getAppkey(), getAppsecret());
            TaobaokeReportGetRequest req = new TaobaokeReportGetRequest();
            req.setFields("trade_parent_id,trade_id,real_pay_fee,commission_rate,commission,subsidy_rate,subsidy,app_key,outer_code,"
                          + "create_time,status,confirm_time,pay_time,pay_price,num_iid,item_title,item_num,category_id,category_name,shop_title,seller_nick");

            req.setDate(Common.emptyStr(date) ? new SimpleDateFormat("yyyyMMdd").format(new Date()) : date);
            req.setPageNo(pageNo == null ? 1 : pageNo);
            req.setPageSize(pageSize == null ? 20L : pageSize);
            TaobaokeReportGetResponse res = client.execute(req, sessionkey);
            TaobaokeReport r = res.getTaobaokeReport();
            return r;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("Get Taobaoke report fail.", e);
            }
            throw new AppBusinessException("Get Taobaoke report fail.", e);
        }
    }

    /**
     * @author BruceZhang
     * @param originalId    淘宝商品ID
     * @return  淘宝商品信息
     * @throws AppBusinessException
     */
    @Override
    public ProductBs convertTaobao(String originalId) throws Exception {
        ProductBs pro = new ProductBs();
        TaobaoClient client = new DefaultTaobaoClient(getUrl(), getAppkey(), getAppsecret());
        ItemGetRequest req = new ItemGetRequest();
        req.setFields("title,price,pic_url,item_img,approve_status,item_imgs");
        req.setNumIid(Long.parseLong(originalId));
        ItemGetResponse response = client.execute(req, null);
        Item item = response.getItem();
        pro.setName(item.getTitle());
        pro.setPrice(Double.parseDouble(item.getPrice()));
        pro.setPicUrl(item.getPicUrl());
        pro.setLinkUrl("http://item.taobao.com/item.htm?id=" + originalId);
        pro.setFrom(DoingProductFrom.TAOBAO.getValue());
        pro.setOriginalId(originalId);
        pro.setMaxPrice(Double.parseDouble(item.getPrice()));
        pro.setImgs(item.getItemImgs());
        //设置商品状态
        if ("onsale".equals(item.getApproveStatus())) {
            pro.setStatus(DoingProductStatus.ONSALE.getValue());
        } else {
            pro.setStatus(DoingProductStatus.NOSALE.getValue());
        }
        return pro;
    }

    @Override
    public PageModel getTaobaokeReport(Map<String, Object> params) throws AppBusinessException {
        int count = topDao.countTaobaokeReportList(params);
        Object pageObj = params.get("page");
        int page = Integer.parseInt(String.valueOf(pageObj));
        if (null == pageObj) {
            params.put("page", 1);
        } else {
            params.put("page", page);
        }
        Object pageSizeObj = params.get("pageSize");
        int pageSize = Integer.parseInt(String.valueOf(pageSizeObj));
        if (null == pageSizeObj) {
            params.put("pageSize", "20");
        } else {
            params.put("pageSize", pageSize);
        }
        params.put("startId", (page - 1) * pageSize);
        List<cn.sumpu.app.guoguojie.domain.TaobaokeReport> trlList = topDao.getTaobaokeReportList(params);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(trlList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }

    @Override
    public void rebate() throws AppBusinessException {
        try {
            Map<String, Object> map = new HashMap<String, Object>();//FIXME 数据量大时可能导致内存溢出
            map.put("guoguojieRebate", false);//FIXME 数据量大时可能导致内存溢出
            List<cn.sumpu.app.guoguojie.domain.TaobaokeReport> trList = topDao.getTaobaokeReportList(map);//FIXME 数据量大时可能导致内存溢出
            if (null != trList && trList.size() > 0) {
                for (cn.sumpu.app.guoguojie.domain.TaobaokeReport tr : trList) {
                    String memberId = tr.getMember();
                    double guoguojieCommissionRate = 0d;
                    if (!Common.emptyStr(tr.getGuoguojieCommissionRate())) {
                        guoguojieCommissionRate = Double.parseDouble(tr.getGuoguojieCommissionRate());
                    }
                    double commission = tr.getCommission();
                    if (!Common.emptyStr(memberId) && guoguojieCommissionRate > 0 && commission > 0) {
                        DefaultTransactionDefinition def = new DefaultTransactionDefinition();// 事务定义类
                        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 设置事务传播属性
                        def.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);// 设置事务隔离级别
                        def.setTimeout(10);// 设置事务超时时间
                        TransactionStatus status = transactionManager.getTransaction(def);// 返回事务对象
                        try {
                            String summary = "";
                            if (!Common.emptyStr(tr.getNumIid())) {
                                summary = "果果街购物返利【单号：<" + String.valueOf(tr.getNumIid()) + ">】";
                            }
                            if (!Common.emptyStr(tr.getGuoguojieProductId())) {
                                summary = "果果街购物返利【单号：" + tr.getGuoguojieProductId() + "】";
                            }
                            // 果果街入账金额：淘宝联盟返现的佣金金额
                            double rmb = commission;

                            // 果果街账户入账
                            if (rmb > 0) {
                                accountBiz.depositRmbByMemberId(Common.GUOGUOJIE_ACCOUNT, rmb, summary, "system", TransactionType.RMB_REBATE);
                            } else {
                                if (logger.isWarnEnabled()) {
                                    logger.warn("Guoguojie rebate incorrect[commission=" + rmb + "]");
                                }
                            }

                            // 果果街账户转帐到会员账户
                            double gcom = commission * guoguojieCommissionRate;
                            if (gcom > 0 && gcom < rmb) {
                                accountBiz.transferRmbByMemberId(Common.GUOGUOJIE_ACCOUNT, memberId, gcom, summary, "system", TransactionType.RMB_REBATE);
                                // 更新报表状态
                                tr.setGuoguojieCommission(gcom);
                                tr.setGuoguojieRebate(true);
                                topDao.updateTaobaokeReport(tr);
                                Member member = memberBiz.getMemberById(memberId);// 发站内信
                                messageBiz.addClientFeedback(null, member.getNickname(), summary);// 发站内信
                            } else {
                                if (logger.isWarnEnabled()) {
                                    logger.warn("Guoguojie rebate incorrect[commission=" + rmb + ",guoguojieCommission=" + gcom + "]");
                                }
                            }

                            transactionManager.commit(status);// 提交事务
                        } catch (Exception e) {
                            if (logger.isErrorEnabled()) {
                                logger.error("Gguoguojie rebate fail," + tr.toString(), e);
                            }
                            transactionManager.rollback(status);// 回滚事务
                        }
                    }
                }
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("Rebate fail", e);
            }
        }

    }

    public static void main(String[] args) {
        double rate = 21.002;
        System.err.println((int) Math.floor(rate));

    }
}
